//
//  PhotoListViewController.m
//  LegalObserver
//
//  Created by Roxanne Brittain on 10/30/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "PhotoListViewController.h"
#import <AudioToolbox/AudioServices.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "LOAppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import "LOMedia.h"
#import "MediaDetailViewController.h"

#define kTagExpanded 3

@implementation PhotoListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = [UIColor whiteColor];
        self.title = @"Camera";
        self.tabBarItem.image = [UIImage imageNamed:@"86-camera"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNew)];
    
    scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:scrollView];
    
    mediaArray = [LOAppDelegate getMediaArray];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self setupMediaDisplay];
}

-(void)setupMediaDisplay
{    
    for (UIView *subview in [scrollView subviews]) [subview removeFromSuperview];

    float width = self.view.frame.size.width;
    
    float w = 75;
    int n = (int) floorf(width/w);
    float s = (width - (w*n)) / (n+1);
    int top, left;
    
    for (int i=0; i<mediaArray.count; i++) {
        LOMedia *media = [mediaArray objectAtIndex:i];
        UIImage *image = [media thumbnailImage];
        
        top = s + (w+s) * ((i-i%n)/n);
        left = s + (w+s) * (i%n);
        
        UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        imageButton.frame = CGRectMake(left, top, 75, 75);
        [imageButton addTarget:self action:@selector(imageButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
        
        [imageButton setImage:image forState:UIControlStateNormal];
        [imageButton setContentMode:UIViewContentModeScaleAspectFill];
        [imageButton.imageView setContentMode:UIViewContentModeScaleAspectFill];
        
        imageButton.layer.borderColor = [UIColor grayColor].CGColor;
        imageButton.layer.borderWidth = .5;
        imageButton.tag = i;
        [scrollView addSubview:imageButton];
    }
    scrollView.contentSize = CGSizeMake(width, top + 79);
}

-(void)imageButtonSelected:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    //    LOMedia *media = [[LOAppDelegate getMediaArray] objectAtIndex: button.tag];
    MediaDetailViewController *detailViewController = [[MediaDetailViewController alloc] initWithMediaIndex:button.tag];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:detailViewController];
    
    nc.navigationBar.tintColor = [UIColor redColor];
    nc.toolbarHidden = NO;
    nc.toolbar.tintColor = [UIColor redColor];
    // ...
    // Pass the selected object to the new view controller.
    [self presentModalViewController:nc animated:YES];
    
}

-(void)addNew
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Media Source" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take Photo or Video", @"Choose from Library", nil];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) [self takePhotoOrVideo];
    else if (buttonIndex==1) [self chooseFromLibrary];
}

-(void)takePhotoOrVideo
{
    [self startCameraControllerFromViewController:self usingDelegate:self];
}

-(void)chooseFromLibrary
{
    [self startMediaBrowserFromViewController: self usingDelegate: self];
}

- (BOOL) startCameraControllerFromViewController:(UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate 
{
    
    if (([UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera] == NO)
        || (delegate == nil)
        || (controller == nil))
        return NO;
    
    
    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    // Displays a control that allows the user to choose picture or
    // movie capture, if both are available:
    cameraUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
    cameraUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, (NSString *) kUTTypeMovie, nil];
    
    // Hides the controls for moving & scaling pictures, or for
    // trimming movies. To instead show the controls, use YES.
    cameraUI.allowsEditing = NO;
    
    cameraUI.delegate = delegate;
    
    [controller presentModalViewController: cameraUI animated: YES];
    return YES;
}

- (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate {
    
    if (([UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
        || (delegate == nil)
        || (controller == nil))
        return NO;
    
    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    // Displays saved pictures and movies, if both are available, from the
    // Camera Roll album.
    mediaUI.mediaTypes =
    [UIImagePickerController availableMediaTypesForSourceType:
     UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    
    // Hides the controls for moving & scaling pictures, or for
    // trimming movies. To instead show the controls, use YES.
    mediaUI.allowsEditing = NO;
    
    mediaUI.delegate = delegate;
    
    [controller presentModalViewController: mediaUI animated: YES];
    return YES;
}

// For responding to the user tapping Cancel.
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    [self dismissModalViewControllerAnimated: YES];
}

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
    {
        
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
            UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
        [LOAppDelegate addImage:imageToSave];
    }
    
    // Handle a movie capture
    if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) 
    {
        NSURL *movieURL = [info objectForKey: UIImagePickerControllerMediaURL];
        NSString *moviePath = [movieURL path];
        
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
            if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
                UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
            [LOAppDelegate addVideoURL:movieURL];
        }
    }
    
    mediaArray = [LOAppDelegate getMediaArray];
    [self dismissModalViewControllerAnimated: YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self setupMediaDisplay];
}

@end
